﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.StrippingCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.StrippingCommandHandler
{
    public class UpdStrippingProductCommandHandler : IRequestHandler<UpdStrippingProductCommand, int>
    {

        IStrippingRepository sRep;
        IStripProductRepostory spRep;
        ISqlSugarClient db;
        IMapper mapper;

        public UpdStrippingProductCommandHandler(IStrippingRepository sRep,
        IStripProductRepostory spRep, ISqlSugarClient db, IMapper mapper)
        {
            this.sRep = sRep;
            this.spRep = spRep;
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<int> Handle(UpdStrippingProductCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //修改生产补料
                var se = await db.Queryable<Stripping>()
                                 .Where(c => c.StrippingId == request.UpdDto.StrippingId)
                .FirstAsync();

                var procurement1 = mapper.Map<Stripping>(request.UpdDto);
                var taskToAdd = await sRep.UpdAsync(procurement1);


                //删除采购退货中的数据
                var itemsToDelete = await db.Queryable<StripProduct>()
                                  .Where(c => c.StripNumber == se.StripNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await spRep.DelRange(new List<StripProduct> { item });
                }


                //修改采购退货产品
                foreach (var item in request.UpdDto.strippingProducts)
                {
                    StripProduct detail = new StripProduct();
                    detail.ProductId = item.ProductId;
                    detail.StripNumber = se.StripNumber;
                    detail.StripProductNum = item.StripProductNum;
                    await spRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
